import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { timeout } from 'rxjs/operators';
import { AuthException, TimeoutException } from '../handler/exception/exception';

@Injectable({
  providedIn: 'root'
})
export class BaseService {

  constructor(
    protected http: HttpClient
  ) { }

  private timeout: number = 20 * 1000;
  private pRemoteAddress = 'http://8070.dev.zepride.com';
  // private pRemoteAddress = 'http://192.168.1.188:8070';
  get uploadUrl() {
    // return this.pRemoteAddress + '/';
    return '';
  }
  get remoteAddress() {
    const address = localStorage.getItem('address');
    if (!address) {
      return this.pRemoteAddress;
    } else {
      return address;
    }
  }

  get token() {
    return localStorage.getItem('token');
  }

  set token(token) {
    localStorage.setItem('token', token);
  }
  get orgid() {
    return localStorage.getItem('orgid');
  }

  public get loginUser() {
    let user = localStorage.getItem('userInfo');
    let result;
    if (user) {
      try {
        return JSON.parse(user);
      } catch (error) {

      }
    }
    return result;
  }

  set orgid(orgid) {
    localStorage.setItem('orgid', orgid);
  }
  get headers() {
    const token = this.token;
    const orgid = this.orgid;
    const headersParams: any = {

    };
    if (token) {
      headersParams.token = token;

    }
    if (orgid) {
      headersParams.orgid = orgid;
    }

    if (this.loginUser) {
      headersParams.userid = this.loginUser.id;
    }


    return headersParams;
  }

  getDefaultHeaders() {
    let headers: HttpHeaders;
    const headersParams = this.headers;
    headers = new HttpHeaders(headersParams);
    return headers;
  }

  get(url: string, options?: {
    isAbsoluteUrl?: boolean;
    headers?: HttpHeaders | {
      [header: string]: string | string[];
    };
    params?: HttpParams | {
      [param: string]: string | string[] | number;
    };
  }): Promise<any> {
    if (options && options.isAbsoluteUrl) {

    }
    else {
      url = `${this.remoteAddress}/${url}`;
    }

    const headers = this.getDefaultHeaders();
    const reqOptions: any = { headers };
    if (options && options.params) {
      reqOptions.params = options.params;
    }
    return new Promise((resolve, reject) => {
      this.http.get(url, reqOptions)
        .pipe(timeout(this.timeout))
        .subscribe(
          data => {
            resolve(data);
          },
          error => {
            const stack = error.stack;
            if (stack && stack.toUpperCase().indexOf('TIMEOUT') > -1) {
              reject(new TimeoutException(500, '请求服务器超时', error));
            } else if (error.status && error.status === 401) {
              reject(new AuthException(401, '登录信息失效', error));
            } else {
              reject(error);
            }
          }
        );
    });
  }

  post(url: string, body: any, options?: {
    headers?: HttpHeaders | {
      [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
      [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType?: 'json';
    withCredentials?: boolean;
    absolutelyUrl?: boolean
  }): Promise<any> {
    if (!options || !options.absolutelyUrl) {
      url = `${this.remoteAddress}/${url}`;
    }
    const headers = this.getDefaultHeaders();
    options = { ...options, headers };
    return new Promise((resolve, reject) => {
      this.http.post(url, body, options)
        .pipe(timeout(this.timeout))
        .subscribe(
          data => {
            resolve(data);
          },
          error => {
            const stack = error.stack;
            if (stack && stack.toUpperCase().indexOf('TIMEOUT') > -1) {
              reject(new TimeoutException(500, '请求服务器超时', error));
            } else if (error.status && error.status === 401) {
              reject(new AuthException(401, '登录信息失效', error));
            } else {
              reject(error);
            }
          }
        );
    });
  }

  put(url: string, params?: any): Promise<any> {
    url = `${this.remoteAddress}/${url}`;
    const headers = this.getDefaultHeaders();
    return new Promise((resolve, reject) => {
      this.http.put(url, params, { headers })
        .pipe(timeout(this.timeout))
        .subscribe(
          data => {
            // headers.token = data.token.value;
            //  this.token = data.token.value;


            resolve(data);
          },
          error => {
            const stack = error.stack;
            if (stack && stack.toUpperCase().indexOf('TIMEOUT') > -1) {
              reject(new TimeoutException(500, '请求服务器超时', error));
            } else if (error.status && error.status === 401) {
              reject(new AuthException(401, '登录信息失效', error));
            } else {
              reject(error);
            }
          }
        );
    });
  }

  delete(url: string, options?: {
    headers?: HttpHeaders | {
      [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
      [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType?: 'json';
    withCredentials?: boolean;
  }) {
    url = `${this.remoteAddress}/${url}`;
    const headers = this.getDefaultHeaders();
    const reqOptions: any = { headers };
    if (options && options.params) {
      reqOptions.params = options.params;
    }
    return new Promise((resolve, reject) => {
      this.http.delete(url, reqOptions)
        .pipe(timeout(this.timeout))
        .subscribe(
          data => {
            resolve(data);
          },
          error => {
            const stack = error.stack;
            if (stack && stack.toUpperCase().indexOf('TIMEOUT') > -1) {
              reject(new TimeoutException(500, '请求服务器超时', error));
            } else if (error.status && error.status === 401) {
              reject(new AuthException(401, '登录信息失效', error));
            } else {
              reject(error);
            }
          }
        );
    });
  }

  getByOriginUrl(url: string, options?: {
    headers?: HttpHeaders | {
      [header: string]: string | string[];
    };
    params?: HttpParams | {
      [param: string]: string | string[];
    };
  }): Promise<any> {
    const headers = this.getDefaultHeaders();
    const reqOptions: any = { headers };
    if (options && options.params) {
      reqOptions.params = options.params;
    }
    return new Promise((resolve, reject) => {
      this.http.get(url, reqOptions)
        .pipe(timeout(this.timeout))
        .subscribe(
          data => {
            resolve(data);
          },
          error => {
            const stack = error.stack;
            if (stack && stack.toUpperCase().indexOf('TIMEOUT') > -1) {
              reject(new TimeoutException(500, '请求服务器超时', error));
            } else if (error.status && error.status === 401) {
              reject(new AuthException(401, '登录信息失效', error));
            } else {
              reject(error);
            }
          }
        );
    });
  }

  postByOriginUrl(url: string, params: any): Promise<any> {
    const headers = this.getDefaultHeaders();
    return new Promise((resolve, reject) => {
      this.http.post(url, params, { headers })
        .pipe(timeout(this.timeout))
        .subscribe(
          data => {
            resolve(data);
          },
          error => {
            const stack = error.stack;
            if (stack && stack.toUpperCase().indexOf('TIMEOUT') > -1) {
              reject(new TimeoutException(500, '请求服务器超时', error));
            } else if (error.status && error.status === 401) {
              reject(new AuthException(401, '登录信息失效', error));
            } else {
              reject(error);
            }
          }
        );
    });
  }

}
